<!-- 密集架移动的组件 -->
<template>
  <div class="body-right">
    <div class="body-right-box">
      <div class="select-box">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-select v-model="selectCabinet" clearable placeholder="请选择" size="mini" :popper-append-to-body="false"
              @change="getCabinetCol(selectCabinet)">
              <el-option v-for="item in cabinetList" :key="item.deviceId" :label="item.deviceName"
                :value="item.deviceId">
              </el-option>
            </el-select>
          </el-col>
        </el-row>
      </div>


      <el-empty v-show="cabinetList.length == 0" :image="import('../assets/no_data.png')"
        description="暂无密集架数据，请重新登陆！"></el-empty>
      <div class="mjj-box" v-show="!cabinetList.length == 0" ref="mjjbox">
        <div class="mjj-item" :style="{
          width: getMjjboxWidth,
          'margin-left': getMarginLeft(),
        }">
          <div v-for="(item, index) in colItemList" :key="item.colId" @click="oneSelectMjj(item, cabinetList)" :class="[
            'mjj',
            {
              isActive: item == currentItem,
              'move-initial': item.moveFlag == 0,
              'move-right': item.moveFlag == 1,
              'move-left': item.moveFlag == -1,
            },
          ]" :style="{
            transform:
              item.moveFlag === 2 || item.moveFlag === -2
                ? `translateX(${(index - colItemList.findIndex((x) => x.fixedFlag === 1)) * 0.1
                }rem)`
                : '',
            transition: moveStatus ? 'transform 8s' : '',
          }">


            <em class="mjj-text" style="font-family: DSDIGIT; top: 29%; color: #ff0604; font-size: 0.1rem">{{
              formattedFourDigitNumber(item.colNo) }}</em>
            <img v-if="item.fixedFlag == 1"
              :src="`${item.picUrl ? `${uploadURL}/mjj/${item.picUrl}` : getLocalImageUrl(item.fixedFlag)}`" class="
              mjj-img no-select" style="width: 100%; height: 100%" />
            <img v-else :src="`${item.picUrl ? `${uploadURL}/mjj/${item.picUrl}` : getLocalImageUrl(item.fixedFlag)
              }`" class="mjj-img no-select" style="width: 100%; height: 100%" />
          </div>
        </div>
      </div>
      <div class="move-button" v-show="IsLogin">
        <el-button :disabled="canClick" @click="handleVent" round v-show="showMoveButton('vent')"
          class="iconfont icon-a-28tongfengfengshan">
        </el-button>
        <el-button :disabled="canClick" @click="handleLeft(currentItem)" round v-show="showMoveButton('moveLeft')"
          class="iconfont icon-zuoyi">
        </el-button>
        <el-button type="primary" :disabled="canClick" @click="handleOpenSelf(currentItem, cabinetList)" round
          v-show="showMoveButton('openCol')" class="iconfont icon-kaimen">
        </el-button>
        <el-button :disabled="canClick" @click="handleCloseSlef" round v-show="showMoveButton('close')"
          class="iconfont icon-guanmen">
        </el-button>
        <el-button :disabled="canClick" @click="handleRight(currentItem)" round v-show="showMoveButton('moveRight')"
          class="iconfont icon-youyi">
        </el-button>
        <el-button :disabled="canClick" @click="handleUnLock" round v-show="showMoveButton('unlock')"
          :class="['iconfont', LockFlag ? 'icon-suoding' : 'icon-jiesuo']">
        </el-button>
        <el-button :disabled="canClick" @click="handleSleep" round v-show="showMoveButton('sleep')"
          :class="['iconfont', sleepFlag ? 'icon-xiumian' : 'icon-huanxing']">
        </el-button>
      </div>


    </div>
  </div>
</template>

<script>
import move from '@/utils/move'
import { virtualRepositoryCabinet, basCabinetCol } from '@/api/rfid/virtualRepository'
import { getButtons, cabinetGeneral } from '@/api/openApi'

import { pagedeviceCabinetList } from '@/api/bas/cabinet.js'
import mjjFix from '../assets/mjj_fix.png'
import mjjP from '../assets/mjj_p.png'

export default {
  name: 'mjjMove',
  components: {},
  props: {
    IsLogin: {
      type: Boolean,
      required: true,
    },
  },
  data() {
    return {
      colItemList: [],
      selectCabinet: '',
      cabinetList: [],
      currentItem: null,
      LockFlag: true, //解锁标识
      sleepFlag: true, //休眠标识
      canClick: false, // 允许点击
      isOutScreen: false, // 判断是否能超出屏幕
      ButtonList: [],
      nowCabinet: {},
      VentFlag: true, //通风的标识
      moveStatus: false, //默认移动的状态
    }
  },
  computed: {
    // 手动计算密集架盒子的宽度
    getMjjboxWidth() {
      return this.colItemList.length > 10 ? `${this.colItemList.length * 50}px` : 'auto'
    },
    formattedFourDigitNumber() {
      /**
       * 格式化数字为四位数。如果数字本身是1-999之间的数，
       * 则在其前面补足零至四位；如果是四位数或以上，则直接返回该数字。
       */

      return function (val) {
        const numStr = String(val)
        const paddingLength = 4 - numStr.length
        // 确保只对不足四位的数字进行补零
        return paddingLength > 0 ? `0`.repeat(paddingLength) + numStr : numStr
      }
    },
  },
  watch: {
    colItemList(newVal, oldVal) {
      if (newVal.length < 10) {
        this.isOutScreen = false
      }
    },
    IsLogin(newVal, oldVal) {
      setTimeout(() => {
        this.$refs.mjjbox.scrollLeft = 400
      }, 200)
    },
  },

  mounted() {
    this.getAllCabinet()
    new move(this.$refs.mjjbox)


  },
  methods: {
    getMarginLeft() {
      return this.colItemList.length > 9
        ? `${this.colItemList.findIndex((x) => x.fixedFlag === 1) * 0.1}rem`
        : '0'
    },
    // 获取装具的列
    getCabinetCol(data) {
      this.moveStatus = false //默认移动的状态
      this.ButtonList = []
      const hasToken = localStorage.getItem('X-Access-Token')
      if (hasToken) {
        virtualRepositoryCabinet(data)
          .then((res) => {
            if (res.data.code == 200) {


              // 获取固定列的索引
              this.colItemList = res.data.data.children.map((x) => {
                return {
                  ...x,
                  moveFlag: 0,
                  // 判断使用哪个图片
                  picUrl: x.fixedFlag == 1 ? res.data.data.fixedColUrl : res.data.data.moveColUrl,
                }
              })
              this.nowCabinet = this.cabinetList.filter(
                (item) => item.deviceId == this.selectCabinet
              )
              this.getMjjBtn(res.data.data)
            }
          })
          .catch((err) => {
            this.$message.error(err.message)
          })
      } else {
        basCabinetCol(data)
          .then((res) => {
            if (res.data.code == 200) {
              // 获取固定列的索引
              this.colItemList = res.data.data
              // this.getMjjBtn(res.data.data)
            } else {
              this.$message.error(res.data.message)
            }
          })
          .catch((err) => {
            this.$message.error(err.message)
          })
      }
    },
    // 获取全部装具的数据
    getAllCabinet() {
      // const hasToken = localStorage.getItem('X-Access-Token')
      // if (hasToken) {
      pagedeviceCabinetList()
        .then((res) => {
          if (res.data.code == 200) {
            this.cabinetList = res.data.data
            if (this.cabinetList.length > 0) {
              this.selectCabinet = this.cabinetList[0].deviceId
              this.getCabinetCol(this.selectCabinet)
            }
          }
        })
        .catch((err) => {
          this.$message.error(err.message)
        })
      // }
    },
    getLocalImageUrl(flag) {
      const imagePath = flag == 1 ? mjjFix : mjjP;
      return imagePath
    },
    /**=================================密集架移动的逻辑开始 */
    // 单击选中密集架事件
    oneSelectMjj(item) {
      if ((this.currentItem ? this.currentItem : '') == item) {
        this.currentItem = null
      } else {
        this.currentItem = item
      }
    },
    // 获取密集架的按钮
    getMjjBtn(item) {
      getButtons({ brandCode: item.brandCode, version: item.verNo }).then((res) => {
        if (res.data.code == 0) {
          this.ButtonList = res.data.data
        } else {
          this.ButtonList.length = 0
        }
      })
    },
    // 根据接口显示需要移动的按钮
    showMoveButton(val) {
      return this.ButtonList.some((obj) => obj.method === val)
    },
    // 通用方法
    handleMethod(methods, data) {
      // if (methods !== 'getHumiture') {
      //   this.moveStatus = true
      // }
      // let params = {
      //   brandCode: data.brandCode,
      //   method: methods,
      //   ip: data.deviceIp,
      //   port: data.devicePort,
      //   quNo: data.quNo,
      //   colNo: this.currentItem ? this.currentItem.colNo : null,
      //   zyNo: data.zyType,
      //   leNo: data.leNum,
      //   diyNo: data.divNum,
      //   version: data.verNo, //  版本协议
      // }
      // return cabinetGeneral(params)
      //   .then((res) => {
      //     if (res.data.code == 0) {
      //       return true
      //     } else {
      //       return false
      //     }
      //   })
      //   .catch((err) => {
      //     return false
      //   })
      return true
    },
    // 打开的逻辑
    async handleOpenSelf(item, device) {
      const result = await this.handleMethod('openCol', this.nowCabinet[0])
      if (result) {
        if (this.VentFlag) {
          if (item.moveFlag == 0) {
            if (item.colNo > device.fixedColNo) {
              if (item.moveFlag == 0) {
                this.handleRightAnimation(item, device)
              } else if (item.moveFlag == 1) {
                this.handleLeftAnimation(item, device)
              }
            } else if (item.colNo < device.fixedColNo) {
              if (item.moveFlag == 0) {
                this.handleLeftAnimation(item, device)
              } else if (item.moveFlag == -1) {
                this.handleRightAnimation(item, device)
              }
            }
          } else {
            this.$message.error('密集架已经在打开状态了，请先合架再打开')
          }
        } else {
          this.$message.error('请先合架，之后在进行操作')
        }
      } else {
        this.$message.error('接口请求失败，请检查后重新尝试···')
      }
    },
    // 通风的逻辑
    async handleVent() {
      const result = await this.handleMethod('vent', this.nowCabinet[0])
      if (result) {
        this.VentFlag = false

        if (this.LockFlag) {
          this.canClick = true
          let loopCount = 0 // 添加计数器
          let fixedIndex = this.colItemList.findIndex((x) => x.fixedFlag === 1)
          for (let i = 0; i < fixedIndex + 1; i++) {
            loopCount++
            setTimeout(() => {
              this.colItemList[i].moveFlag = -2
            }, (loopCount - 1) * 1000)
          }
          this.isOutScreen = true

          let loopCountLeft = loopCount
          // 重新将loopCount置空
          loopCount = 0
          for (let i = this.colItemList.length - 1; i >= fixedIndex; i--) {
            loopCount++
            setTimeout(() => {
              this.colItemList[i].moveFlag = 2
            }, (loopCount - 1) * 1000)
          }
          let maxValue = Math.max(loopCountLeft, loopCount)
          setTimeout(() => {
            this.canClick = false
          }, maxValue * 1000)
        } else {
          this.$message.error('请先锁定密集架')
        }
      } else {
        this.$message.error('接口请求失败，请检查后重新尝试···')
      }
    },
    // 左移的逻辑
    async handleLeft(item, device) {
      const result = await this.handleMethod('moveLeft', this.nowCabinet[0])
      if (result) {
        if (this.VentFlag) {
          if (this.LockFlag) {
            let loopCount = 0 // 添加计数器
            this.canClick = true
            // 当前点击的索引
            const index = this.colItemList.findIndex((x) => x.colNo === item.colNo)
            // 固定列的索引
            let fixedIndex = this.colItemList.findIndex((x) => x.fixedFlag === 1)
            if (index > fixedIndex) {
              // console.log('在固定列右边')
              for (let i = 0; i < index + 1; i++) {
                let isIWithinRange =
                  fixedIndex < index ? fixedIndex < i && i <= index : index <= i && i <= fixedIndex
                if (this.colItemList[i].moveFlag == 1 && isIWithinRange) {
                  loopCount++
                  setTimeout(() => {
                    this.colItemList[i].moveFlag = 0
                  }, (loopCount - 1) * 1000)
                }
              }
            } else if (index < fixedIndex) {
              // console.log('在固定列左边')
              if (index !== -1) {
                for (let i = 0; i < index + 1; i++) {
                  if (this.colItemList[i].moveFlag !== -1) {
                    loopCount++
                    setTimeout(() => {
                      this.colItemList[i].moveFlag = -1
                    }, (loopCount - 1) * 1000)
                  }
                }
              }
              this.isOutScreen = true
            } else if (item.colNo == undefined) {
              this.$message.error('请选择密集架，之后再进行操作')
            } else {
              this.$message.error('当前是固定列，无法移动')
            }
            setTimeout(() => {
              this.canClick = false
            }, loopCount * 1000)
          } else {
            this.$message.error('请先锁定密集架')
          }
        } else {
          this.$message.error('请先合架，之后在进行操作')
        }
      } else {
        this.$message.error('接口请求失败，请检查后重新尝试···')
      }
    },
    // 左移的动画
    async handleLeftAnimation(item, device) {
      if (this.LockFlag) {
        let needMove = this.cabinetList[0].children
        let loopCount = 0 // 添加计数器
        this.canClick = true

        const index = needMove.findIndex((x) => x.colNo === item.colNo)
        // 获取固定列的索引
        const fixedIndex = needMove.findIndex((x) => x.fixedFlag === 1)
        if (item.colNo > device.fixedColNo) {
          // console.log('在固定列右边')
          for (let i = 0; i < index + 1; i++) {
            let isIWithinRange =
              fixedIndex < index ? fixedIndex < i && i <= index : index <= i && i <= fixedIndex
            if (needMove[i].moveFlag == 1 && isIWithinRange) {
              loopCount++
              setTimeout(() => {
                needMove[i].moveFlag = 0
              }, (loopCount - 1) * 1000)
            }
          }
        } else if (item.colNo < device.fixedColNo) {
          // console.log('在固定列左边')
          if (index !== -1) {
            for (let i = 0; i < index + 1; i++) {
              if (needMove[i].moveFlag !== -1) {
                loopCount++
                setTimeout(() => {
                  needMove[i].moveFlag = -1
                }, (loopCount - 1) * 1000)
              }
            }
          }
        } else if (item.colNo == undefined) {
          this.$message.error('请选择密集架，之后再进行操作')
        }
        // 等待动画时间结束之后
        setTimeout(() => {
          this.canClick = false
        }, loopCount * 1000)
      } else {
        this.$message.error('请先锁定密集架')
      }
    },
    // 合架的逻辑
    async handleCloseSlef() {
      const result = await this.handleMethod('close', this.nowCabinet[0])
      if (result) {
        this.VentFlag = true

        if (this.LockFlag) {
          let loopCount = 0 // 添加计数器
          this.canClick = true
          // 固定列的索引
          let fixedIndex = this.colItemList.findIndex((x) => x.fixedFlag === 1)
          // 密集架左侧的关闭动画
          for (let i = fixedIndex; i >= 0; i--) {
            if (this.colItemList[i].moveFlag == -1 || this.colItemList[i].moveFlag == -2) {
              loopCount++
              setTimeout(() => {
                this.colItemList[i].moveFlag = 0
              }, (loopCount - 1) * 1000)
            }
          }
          let loopCountLeft = loopCount
          // 密集架右侧侧的关闭动画
          loopCount = 0 //需要置空
          for (let i = fixedIndex; i < this.colItemList.length; i++) {
            if (this.colItemList[i].moveFlag == 1 || this.colItemList[i].moveFlag == 2) {
              loopCount++
              setTimeout(() => {
                this.colItemList[i].moveFlag = 0
              }, (loopCount - 1) * 1000)
            }
          }
          let maxValue = Math.max(loopCountLeft, loopCount)
          setTimeout(() => {
            this.canClick = false
          }, maxValue * 1000)
        } else {
          this.$message.error('请先锁定密集架')
        }
      } else {
        this.$message.error('接口请求失败，请检查后重新尝试···')
      }
    },
    // 右移的逻辑
    async handleRight(item, device) {
      const result = await this.handleMethod('moveRight', this.nowCabinet[0])
      if (result) {
        if (this.VentFlag) {
          if (this.LockFlag) {
            let loopCount = 0 // 添加计数器
            this.canClick = true
            // 当前点击的索引
            const index = this.colItemList.findIndex((x) => x.colNo === item.colNo)
            // 固定列的索引
            let fixedIndex = this.colItemList.findIndex((x) => x.fixedFlag === 1)

            if (index > fixedIndex) {
              // console.log('在固定列右边')
              for (let i = this.colItemList.length - 1; i >= 0; i--) {
                if (this.colItemList[i].moveFlag == 0 && index <= i) {
                  loopCount++
                  setTimeout(() => {
                    this.colItemList[i].moveFlag = 1
                  }, (loopCount - 1) * 1000)
                }
              }
            } else if (index < fixedIndex) {
              // console.log('在固定列左边')
              for (let i = this.colItemList.length - 1; i >= 0; i--) {
                if (this.colItemList[i].moveFlag == -1 && index <= i) {
                  loopCount++
                  setTimeout(() => {
                    this.colItemList[i].moveFlag = 0
                  }, (loopCount - 1) * 1000)
                }
              }
            } else if (item.colNo == undefined) {
              this.$message.error('请选择密集架，之后再进行操作')
            } else {
              this.$message.error('当前是固定列，无法移动')
            }
            setTimeout(() => {
              this.canClick = false
            }, loopCount * 1000)
          } else {
            this.$message.error('请先锁定密集架')
          }
        } else {
          this.$message.error('请先合架，之后在进行操作')
        }
      } else {
        this.$message.error('接口请求失败，请检查后重新尝试···')
      }
    },
    // 右移的动画
    async handleRightAnimation(item, device) {
      if (this.LockFlag) {
        let needMove = this.cabinetList[0].children
        let loopCount = 0 // 添加计数器
        this.canClick = true

        const index = needMove.findIndex((x) => x.colNo === item.colNo)
        if (item.colNo > device.fixedColNo) {
          // console.log('在固定列右边')
          for (let i = needMove.length - 1; i >= 0; i--) {
            if (needMove[i].moveFlag == 0 && index <= i) {
              loopCount++
              setTimeout(() => {
                needMove[i].moveFlag = 1
              }, (loopCount - 1) * 1000)
            }
          }
        } else if (item.colNo < device.fixedColNo) {
          // console.log('在固定列左边')
          for (let i = needMove.length - 1; i >= 0; i--) {
            if (needMove[i].moveFlag == -1 && index <= i) {
              loopCount++
              setTimeout(() => {
                needMove[i].moveFlag = 0
              }, (loopCount - 1) * 1000)
            }
          }
        } else if (item.colNo == device.fixedColNo) {
          this.$message.error('当前是固定列，请不要移动')
        }
        // 等待动画时间结束之后
        setTimeout(() => {
          this.canClick = false
        }, loopCount * 1000)
      } else {
        this.$message.error('请先锁定密集架')
      }
    },
    // 解锁的逻辑
    handleUnLock() {
      this.LockFlag = !this.LockFlag
      if (this.LockFlag) {
        this.$message.success('解锁成功')
      } else {
        this.$message.warning('已锁定')
      }
    },
    // 休眠的逻辑
    handleSleep() {
      this.sleepFlag = !this.sleepFlag
      if (this.sleepFlag) {
        this.$message.success('已唤醒')
      } else {
        this.$message.warning('已休眠')
      }
    },

    /**=================================密集架移动的逻辑结束 */
  },
}
</script>
<style lang="less" scoped>
.con {
  height: 100%;

  .sys-body {
    position: relative;
    height: 50%;
    width: 100%;

    .body-right {
      --mjjheight: 60%;
      --selctheight: 15%;

      position: absolute;
      right: 50px;
      width: 40%;
      height: 100%;

      .body-right-box {
        .select-box {
          height: var(--selctheight);
          padding: 10px 0 0 10px;
        }

        // flex布局的代码
        .mjj-box {
          height: 60%;
          overflow-x: auto;
          /* 允许横向滚动 */
          white-space: nowrap;

          .mjj-item {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100%;

            .mjj {
              display: flex;
              width: 50px;
              height: auto;
              margin: 0 2px;
              justify-content: space-around;
              position: relative;
            }
          }
        }

        // 这里进行定位测试代码
        // .mjj-box {
        //   height: 60%;
        //   width: 100%;
        //   overflow-x: auto; /* 允许横向滚动 */
        //   white-space: nowrap;
        //   .mjj-item {
        //     position: relative;
        //     .mjj {
        //       position: absolute;
        //       // 居中
        //       top: 50%;
        //       left: 50%;
        //       transform: translate(-50%);

        //       width: 50px;
        //     }
        //   }
        // }

        .move-button {
          margin: 20px 0;

          .el-button {
            color: #00bfff;
            background: #2c5ba985;
            border: 1px solid #12408c;
          }
        }
      }
    }
  }
}

.mjj-img {
  position: relative;
  width: 100%;
  height: 100%;
}

.mjj-text {
  position: absolute;
  // 垂直水平居中
  left: 50%;
  color: #f2f2f2f2;
  transform: translate(-50%, -100%);
  font-size: 0.3rem
    /* 16/192 */
  ;
  font-weight: 700;
  z-index: 99;
}

.body-right-box {
  position: relative;
  background: rgb(21 103 203 / 20%);
  width: 100%;
  height: 100%;
  line-height: 100%;
  text-align: center;
  color: #dddada;
  text-decoration: none;
  font-size: 20px;
}

.body-right-box::before,
.body-right-box::after {
  /* 将两个伪元素的相同样式写在一起 */
  content: '';
  position: absolute;
  width: 20px;
  height: 20px;
  border: 3px solid #38bdea;
  /* 这里也加一个动画过渡 */
  /* 最后的0.3s是延迟时间 */
}

.body-right-box::before {
  top: 0;
  left: 0;
  /* 删除左边元素的右、下边框 */
  border-right: 0;
  border-bottom: 0;
  // box-shadow:-4px -4px 10px #f00;
}

.body-right-box::after {
  right: 0;
  bottom: 0;
  /* 删除右边元素的左、上边框 */
  border-top: 0;
  border-left: 0;
}

.isActive {
  filter: brightness(80%);
  /* 降低亮度 */
}

.select-box {

  // 对element UI的样式进行调整
  :deep(.el-select__wrapper) {
    background: transparent;
    border: 1px solid #67707c;
    color: #fff;
  }

  :deep(.el-select__placeholder) {
    color: #fff;
  }


  .el-input__inner:focus {
    border: 1px solid #38bdea;
  }

  .el-input__inner::placeholder {
    color: #fff;
  }

  .el-select-dropdown__item.hover,
  .el-select-dropdown__item:hover {
    background-color: #38bdea;
    color: #fff;
  }

  .el-select-dropdown__item {
    color: #dddada;
  }

  .el-button {
    background: transparent;
    color: #fff;
  }

  .el-button:hover {
    background: rgb(21 103 203 / 40%);
    color: #fff;
  }

  .el-select-dropdown {
    border: rgb(32, 56, 101);
    background-color: rgb(32, 56, 101);
  }

  .popper__arrow {
    display: none;
  }

  .el-scrollbar__wrap {
    overflow-x: hidden;
  }
}

.custom-empty .el-empty__image {
  /* 更改图片颜色 */
  filter: drop-shadow(0 0 0.25rem red);
}

.custom-empty .el-empty__description {
  /* 更改描述文字颜色 */
  color: blue;
}

// 密集架移动的动画
.move-initial {
  // transition: transform 8s ease-in-out;
  transform: translateX(0);
}

.move-right {
  // transition: transform 8s ease-in-out;
  transform: translateX(0.9rem);
}

.move-left {
  // transition: transform 8s ease-in-out;
  transform: translateX(-0.9rem);
}

.mjj-box::-webkit-scrollbar {
  height: 8px;
  width: 10px;
  background: transparent;
}

.mjj-box::-webkit-scrollbar-track {
  /* -webkit-box-shadow: inset 0 0 6px rgb(221, 217, 217); */
  background-color: rgb(16, 28, 53) !important;
  border-radius: 3px;
}

.mjj-box::-webkit-scrollbar-thumb {
  background-color: rgba(21, 39, 64, 0.8) !important;
  -webkit-border-radius: 2px;
  -moz-border-radius: 2px;
  border-radius: 2px;
}
</style>
